﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IronOne.SalesOne.BusinessObjects;
using System.Configuration;
using Facade;
using System.Web.Security;
using System.Collections;
using IronOne.SalesOne.DataObjects;

namespace IronOne.SalesOne.SalesOneWeb
{
    public partial class UpdateUser : SOSecurityPage
    {
        private string action = "update";

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    ValidateUserCredentials(Request.Url.LocalPath);

                    if (!string.IsNullOrEmpty(Request.UrlReferrer.ToString()))
                    {
                        ViewState["refUrl"] = Request.UrlReferrer.ToString();
                    }



                    CodeFacade coFac = new CodeFacade();
                    List<IDType> id = coFac.GetIDTypes("CodeId ASC", 1);
                    IDType idSel = new IDType();

                    idSel.CodeId = -1;
                    idSel.Description = "Select";
                    id.Insert(0, idSel);

                    drpIdType.DataSource = id;
                    drpIdType.DataTextField = "Description";
                    drpIdType.DataValueField = "CodeId";
                    drpIdType.DataBind();

                    ////////////////////////////



                    //////////////////////////

                    List<Country> coun = coFac.GetCountries("CodeId ASC");
                    //List<Country> coun = coFac.GetCountries("CodeId ASC", 1);
                    Country cSel = new Country();
                    cSel.CodeId = -1;
                    cSel.Description = "Select";
                    coun.Insert(0, cSel);

                    drpCountry.DataSource = coun;
                    drpCountry.DataTextField = "Description";
                    drpCountry.DataValueField = "CodeId";
                    drpCountry.DataBind();



                    string user = Session["userName"].ToString();
                    MembershipUser usr = Membership.GetUser(user);
                    Guid userGuuid = (Guid)usr.ProviderUserKey;

                    StructureFacade userFacade = new StructureFacade();
                    User usrObj = userFacade.GetUser(userGuuid);

                    LinqUser lu = new LinqUser();
                    string intraUsername = lu.IsLinkedUserCheck(usr.UserName.ToLower());

                    if (intraUsername == null)
                    {
                        IntranetUserName.Enabled = true;
                        IntranetUserName.ToolTip = "Warning: Once you assign the Intranet Username you can't change it.";
                    }
                    else
                    {
                        IntranetUserName.Text = intraUsername;
                        IntranetUserName.Enabled = false;
                        IntranetUserName.ToolTip = "";
                    }

                    txtUserName.Text = usr.UserName;
                    txtName.Text = usrObj.Name;
                    txtIdNo.Text = usrObj.IdNo;
                    txtAddress1.Text = usrObj.Address1;
                    txtAddress2.Text = usrObj.Address2;
                    txtCity.Text = usrObj.City;
                    txtContact.Text = usrObj.Contact;
                    txtPostalCode.Text = usrObj.PostalCode.ToString();
                    Email.Text = usr.Email;



                    if (!string.IsNullOrEmpty(usrObj.Country))
                    {
                        drpCountry.SelectedValue = drpCountry.Items.FindByText(usrObj.Country).Value;
                    }

                    if (!string.IsNullOrEmpty(usrObj.IdType))
                    {
                        drpIdType.SelectedValue = drpIdType.Items.FindByText(usrObj.IdType).Value;
                    }

                    drpGender.SelectedValue = usrObj.Gender;



                    //user structure information
                    UserInformation info = userFacade.GetUserInformation(usr.UserName);

                    List<UserType> userTypes = userFacade.GetUserTypes("UserTypeId ASC");

                    rdoUserTypes.DataSource = userTypes;
                    rdoUserTypes.DataTextField = "UserTypeName";
                    rdoUserTypes.DataValueField = "UserTypeId";
                    rdoUserTypes.DataBind();

                    chkUserType.DataSource = userTypes;
                    chkUserType.DataTextField = "UserTypeName";
                    chkUserType.DataValueField = "UserTypeId";
                    chkUserType.DataBind();



                    rdoUserTypes.Items[info.UserType - 1].Selected = true;



                    //set selected roles of a user
                    List<short> uRTypes = userFacade.GetUserTypesOfRolesForUser(usrObj.UserId);
                    ArrayList ar = new ArrayList();

                    foreach (short type in uRTypes)
                    {
                        chkUserType.Items.FindByValue(type.ToString()).Selected = true;
                        ar.Add(Convert.ToInt32(type));

                    }




                    List<UserRole_aspnet> rls = userFacade.GetAllRolesForUserTypes((int[])ar.ToArray(typeof(int)));

                    chkRoles.DataSource = rls;
                    chkRoles.DataTextField = "RoleName";
                    chkRoles.DataValueField = "RoleId";
                    chkRoles.DataBind();

                    string[] roles = Roles.GetRolesForUser(usr.UserName);

                    foreach (ListItem it in chkRoles.Items)
                    {
                        if (roles.Contains(it.Text))
                        {
                            it.Selected = true;
                        }
                    }


                    //




                    //nodes
                    switch (info.UserType)
                    {
                        case 1:


                            break;
                        case 2:

                            FillDropDown("Group");
                            drpGroup.SelectedValue = info.GroupId.ToString();
                            Session["groupId"] = info.GroupId;

                            break;
                        case 3:

                            FillDropDown("Group");
                            drpGroup.SelectedValue = info.GroupId.ToString();

                            FillDropDown("Branch");
                            drpBranch.SelectedValue = info.BranchId.ToString();
                            Session["branchId"] = info.BranchId;

                            break;
                        case 4:

                            FillDropDown("Group");
                            drpGroup.SelectedValue = info.GroupId.ToString();

                            FillDropDown("Branch");
                            drpBranch.SelectedValue = info.BranchId.ToString();

                            FillDropDown("Unit");
                            drpUnit.SelectedValue = info.UnitId.ToString();
                            Session["unitId"] = info.UnitId;

                            break;
                        default:
                            break;
                    }
                    //


                }
            }
            catch (Exception)
            {

            }

        }

        protected void ChangePasswordPushButton_Click(object sender, EventArgs e)
        {
            
            try
            {
                if (drpCountry.SelectedItem.Text == "Select")
                {
                    MassageSummery("IIS501");
                    //FailureText.Text = FailureText.Text + " Please put a valid value for Country ";
                }
                else if (drpIdType.SelectedItem.Text == "Select")
                {
                    MassageSummery("IIS501");
                    //FailureText.Text = FailureText.Text + " Please put a valid value for Country ";
                }
               else if (!string.IsNullOrEmpty(txtContact.Text.Trim()) && txtContact.Text.Trim().Length > 15)
               {
                   MassageSummery("IIS538");
               }
               else
                {
                    StructureFacade usrFac = new StructureFacade();

                    User upUsrObj = new User();

                    string user = Session["userName"].ToString();
                    MembershipUser usr = Membership.GetUser(user);

                    upUsrObj.UserId = (Guid)usr.ProviderUserKey;
                    upUsrObj.Name = txtName.Text;
                    upUsrObj.IdNo = txtIdNo.Text;
                    upUsrObj.Address1 = txtAddress1.Text;
                    upUsrObj.Address2 = txtAddress2.Text;
                    upUsrObj.City = txtCity.Text;
                    upUsrObj.Contact = txtContact.Text.Trim();
                    upUsrObj.DoneBy = System.Web.HttpContext.Current.User.Identity.Name;

                    upUsrObj.PostalCode = txtPostalCode.Text;

                    //if (!string.IsNullOrEmpty(txtPostalCode.Text))
                    //{
                    //    upUsrObj.PostalCode = Convert.ToInt32(txtPostalCode.Text);
                    //}

                    usr.Email = Email.Text;
                    upUsrObj.IdType = drpIdType.SelectedValue;
                    upUsrObj.Gender = drpGender.SelectedValue;
                    upUsrObj.Country = drpCountry.SelectedValue;

                    MembershipUser adUser = Membership.GetUser(User.Identity.Name);
                    Guid adkey = (Guid)adUser.ProviderUserKey;

                    upUsrObj.LastUpBy = adkey.ToString();
                    upUsrObj.LastUpdateDate = DateTime.Now.ToShortDateString();

                   //update the organisational node
                    short userType = (short)Convert.ToInt32(rdoUserTypes.SelectedValue);
                    Guid userGuuid = (Guid)usr.ProviderUserKey;

                    int nodeId = 0;

                    if (rdoUserTypes.SelectedItem.Text == "Group" && drpGroup.SelectedValue != "-1")
                    {
                        nodeId = Convert.ToInt32(drpGroup.SelectedValue);
                        usrFac.UpdateUserInStructure(userGuuid, userType, nodeId);
                    }
                    else if (rdoUserTypes.SelectedItem.Text == "Branch" && drpBranch.SelectedValue != "-1")
                    {
                        nodeId = Convert.ToInt32(drpBranch.SelectedValue);
                        usrFac.UpdateUserInStructure(userGuuid, userType, nodeId);
                    }
                    else if (rdoUserTypes.SelectedItem.Text == "Unit" && drpUnit.SelectedValue != "-1")
                    {
                        nodeId = Convert.ToInt32(drpUnit.SelectedValue);
                        usrFac.UpdateUserInStructure(userGuuid, userType, nodeId);
                    }
                    else if (rdoUserTypes.SelectedItem.Text == "HQ")
                    {
                        usrFac.UpdateUserInStructure(userGuuid, userType, nodeId);
                    }
                    else
                    {
                        
                    }

                   //
                   //update roles
                    if (chkRoles.Items.Count == 0)
                    {
                        
                       
                        //return;

                    }
                    else
                    {
                        foreach (ListItem ci in chkRoles.Items)
                        {
                            if (ci.Selected && !Roles.GetRolesForUser(usr.UserName).Contains(ci.Text))
                            {
                                Roles.AddUserToRole(usr.UserName, ci.Text);
                                //AddUserToRole(wizCreateUser.UserName, chkRoles.Items[i].Text);
                            }
                            else if (!ci.Selected && Roles.GetRolesForUser(usr.UserName).Contains(ci.Text))
                            {
                                Roles.RemoveUserFromRole(usr.UserName, ci.Text);
                            }
                        }

                        //for (int i = 0; i < chkRoles.Items.Count - 1; i++)
                        //{
                        //    if (chkRoles.Items[i].Selected && !Roles.GetRolesForUser(usr.UserName).Contains(chkRoles.Items[i].Text))
                        //    {
                        //        Roles.AddUserToRole(usr.UserName, chkRoles.Items[i].Text);
                        //            //AddUserToRole(wizCreateUser.UserName, chkRoles.Items[i].Text);
                        //    }
                        //    else if (!chkRoles.Items[i].Selected && Roles.GetRolesForUser(usr.UserName).Contains(chkRoles.Items[i].Text))
                        //    {
                        //        Roles.RemoveUserFromRole(usr.UserName, chkRoles.Items[i].Text);

                        //    }
                        //}
                    }
                   //

                    //bool flag = true;

                   // Suren Manawatta
                   // 2012-10-31
                   // Removed the reset password section (it's a new requirement)
                   // All the password changes are doing from their intranet
                    //if (Password.Text != "")
                    //{
                    //   //Membership.UpdateUser(

                    //   string pw = usr.GetPassword();

                    //   flag = usr.ChangePassword(pw, Password.Text);
                    //}


                    //if (flag == true)
                    //{
                        usrFac.UpdateUser(upUsrObj);

                        Membership.UpdateUser(usr);

                        // Suren Manawatta
                        // 2012-11-02
                        // Update the aspnet_Users table's user data (intranet password)
                        if (IntranetUserName.Enabled == true)
                        {
                            LinqUser lu = new LinqUser();
                            bool? rslt = lu.UpdateIntranetUsername(usr.UserName.ToLower().Trim(), IntranetUserName.Text.ToLower().Trim());
                            if (rslt == null)
                            {
                                MassageSummery("IIS547");
                            }

                            if (rslt != null && !(bool)rslt)
                            {
                                MassageSummery("IIS546");
                            }

                            if (rslt != null && (bool)rslt)
                            {
                                Session["uInSuc"] = "1";
                                Response.Redirect(ViewState["refUrl"].ToString());
                            }
                        }
                        
                    //}
                    //else
                    //{
                    //    MassageSummery("IIS501");
                    //    //FailureText.Text = FailureText.Text + " Old password is incorrect ";
                    //}
                    
                }
                
            }
            catch (Exception ex)
            {
                //if (ex.Message == "The length of parameter 'newPassword' needs to be greater or equal to '6'.")
                //{
                //    MassageSummery("IIS520");
                //}
                //throw;
            }
        }

        protected void CancelPushButton_Click(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect(ViewState["refUrl"].ToString());
            }
            catch (Exception)
            {

            }
            
        }

        protected void drpGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (rdoUserTypes.SelectedItem.Text == "Branch" || rdoUserTypes.SelectedItem.Text == "Unit")
                {
                    FillDropDown("Branch");
                }

                if (rdoUserTypes.SelectedItem.Text == "Unit")
                {
                    FillDropDown("Unit");
                }
            }
            catch (Exception)
            {

            }
            

        }

        protected void drpBranch_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (rdoUserTypes.SelectedItem.Text == "Unit")
                {
                    FillDropDown("Unit");
                }
            }
            catch (Exception)
            {

            }
            

        }


        public void FillDropDown(string type)
        {
            try
            {
                StructureFacade fac = new StructureFacade();

                switch (type)
                {
                    case "Group":
                        List<SalesOneGroup> grp = fac.GetGroups("GroupId ASC");
                        SalesOneGroup grsel = new SalesOneGroup();
                        grsel.GroupId = -1;
                        grsel.Name = "Select";
                        grp.Insert(0, grsel);
                        drpGroup.DataSource = grp;
                        drpGroup.DataTextField = "Name";
                        drpGroup.DataValueField = "GroupId";
                        drpGroup.DataBind();
                        break;
                    case "Branch":
                        if (drpGroup.SelectedValue != "-1")
                        {
                            List<Branch> br = fac.GetBranchesForGroup(Convert.ToInt32(drpGroup.SelectedValue));
                            drpBranch.DataSource = br;
                            Branch brSel = new Branch();
                            brSel.BranchId = -1;
                            brSel.BranchName = "Select";
                            br.Insert(0, brSel);
                            drpBranch.DataTextField = "BranchName";
                            drpBranch.DataValueField = "BranchId";
                            drpBranch.DataBind();
                        }
                        else
                        {
                            List<Branch> br = new List<Branch>();
                            drpBranch.DataSource = br;
                            Branch brSel = new Branch();
                            brSel.BranchId = -1;
                            brSel.BranchName = "Select";
                            br.Insert(0, brSel);
                            drpBranch.DataTextField = "BranchName";
                            drpBranch.DataValueField = "BranchId";
                            drpBranch.DataBind();
                        }
                        break;
                    case "Unit":
                        if (drpBranch.SelectedValue != "-1")
                        {
                            List<SalesOneUnit> un = fac.GetUnitsInBranch(Convert.ToInt32(drpBranch.SelectedValue));
                            SalesOneUnit unSel = new SalesOneUnit();
                            unSel.UnitId = -1;
                            unSel.Name = "Select";
                            un.Insert(0, unSel);
                            drpUnit.DataSource = un;
                            drpUnit.DataTextField = "Name";
                            drpUnit.DataValueField = "UnitId";
                            drpUnit.DataBind();
                        }
                        else
                        {
                            List<SalesOneUnit> un = new List<SalesOneUnit>();

                            SalesOneUnit unSel = new SalesOneUnit();
                            unSel.UnitId = -1;
                            unSel.Name = "Select";
                            un.Insert(0, unSel);
                            drpUnit.DataSource = un;
                            drpUnit.DataTextField = "Name";
                            drpUnit.DataValueField = "UnitId";
                            drpUnit.DataBind();

                        }
                        break;
                    default:
                        break;
                }
            }
            catch (Exception)
            {

            }
            
        }

        protected void rdoUserTypes_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (rdoUserTypes.SelectedIndex == 0)
                {//HQ
                    drpUnit.Enabled = false;
                    drpBranch.Enabled = false;
                    drpGroup.Enabled = false;
                }
                else if (rdoUserTypes.SelectedIndex == 1)
                {//Group
                    FillDropDown("Group");
                    FillDropDown("Branch");
                    FillDropDown("Unit");

                    drpUnit.Enabled = false;
                    drpBranch.Enabled = false;
                    drpGroup.Enabled = true;
                }
                else if (rdoUserTypes.SelectedIndex == 2)
                {//Branch
                    FillDropDown("Group");
                    FillDropDown("Branch");
                    FillDropDown("Unit");

                    drpGroup.Enabled = true;
                    drpBranch.Enabled = true;
                    drpUnit.Enabled = false;
                }
                else if (rdoUserTypes.SelectedIndex == 3)
                {//Unit
                    FillDropDown("Group");
                    FillDropDown("Branch");
                    FillDropDown("Unit");

                    drpGroup.Enabled = true;
                    drpBranch.Enabled = true;
                    drpUnit.Enabled = true;
                }
            }
            catch (Exception)
            {

            }
            
        }

        protected void chkUserType_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                string user = Session["userName"].ToString();
                MembershipUser usr = Membership.GetUser(user);

                StructureFacade fac = new StructureFacade();
                ArrayList ar = new ArrayList();


                foreach (ListItem it in chkUserType.Items)
                {
                    if (it.Selected)
                    {
                        ar.Add(Convert.ToInt32(it.Value));
                    }

                }


                List<UserRole_aspnet> rls = fac.GetAllRolesForUserTypes((int[])ar.ToArray(typeof(int)));

                chkRoles.DataSource = rls;
                chkRoles.DataTextField = "RoleName";
                chkRoles.DataValueField = "RoleId";
                chkRoles.DataBind();

                string[] roles = Roles.GetRolesForUser(usr.UserName);

                foreach (ListItem it in chkRoles.Items)
                {
                    if (roles.Contains(it.Text))
                    {
                        it.Selected = true;
                    }
                }
            }
            catch (Exception)
            {

            }
            
        }

        protected void drpCountry_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}
